using log4net;
using Mathmall.Administration.Data;
using Mathmall.Administration.Models;
using Microsoft.EntityFrameworkCore;

namespace Mathmall.Administration.Mapper;

public class CategoryMapper : BaseMapper
{
    public CategoryMapper(AdministrationContext context) : base(context)
    {
    }

    /// <summary>
    /// 添加商品分类
    /// </summary>
    /// <param name="category"></param>
    /// <returns></returns>
    public async Task<int> AddCategory(Category category)
    {
        _context.Add(category);
        return await _context.SaveChangesAsync();
    }

    /// <summary>
    /// 查询全部分类数据
    /// </summary>
    /// <returns></returns>
    public IQueryable<Category> QueryAll()
    {
        return from category in _context.Categories select category;
    }

    /// <summary>
    /// 根据父id查询分类信息
    /// </summary>
    /// <param name="parentCategoryId">父分类的id</param>
    /// <returns>返回分类信息集合</returns>
    public IQueryable<Category> QueryCategoriesByParentId(int? parentCategoryId)
    {
        return _context.Categories.Where(category => category.ParentCID == parentCategoryId);
    }

    /// <summary>
    /// 更新分类信息
    /// </summary>
    /// <param name="updatedCategory"></param>
    /// <returns></returns>
    public async Task<int> UpdateCategory(Category updatedCategory)
    {
        return await _context.Categories.Where(category => category.CategoryID == updatedCategory.CategoryID)
            .ExecuteUpdateAsync(setter => setter.SetProperty(category => category.Name, updatedCategory.Name));
    }

    /// <summary>
    /// 删除分类
    /// </summary>
    /// <param name="categoryIdList"></param>
    /// <returns></returns>
    public async Task<int> DeleteCategories(List<int> categoryIdList)
    {
        return await _context.Categories.Where(category => categoryIdList.Contains(category.CategoryID))
            .ExecuteDeleteAsync();
    }

    /// <summary>
    /// 查询全部分类信息
    /// </summary>
    /// <returns></returns>
    public async Task<List<Category>> GetAllCategories()
    {
        return await _context.Categories.ToListAsync();
    }

    /// <summary>
    /// 根据id查询分类信息
    /// </summary>
    /// <param name="categoryId"></param>
    /// <returns></returns>
    public async Task<Category> GetCategoryById(int categoryId)
    {
        return await _context.Categories.Where(category => category.CategoryID == categoryId).FirstAsync();
    }
}